<?php
namespace App\Http\Services;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Illuminate\Support\Facades\Log;

class APICloudsign
{

    /*
        http://docs.guzzlephp.org/
     */

    private $base_uri = '';
    private $client_id = '';

    private $client = null;

    private $response = array(
        'status_code' => 0,
        'protocol_version' => '',
        'reason' => '',
        'headers' => [],
        'body' => '',
    );
    private $request = array(
        'method' => '',
        'uri' => '',
        // 'host' => '',
        // 'port' => null,
        // 'path' => '',
        // 'query' => '',
        'headers' => [],
        // 'scheme' => '',
    );
    private $request_headers = array();

    /*
     * @param bool $is_prod プロダクション環境なら TRUE
     * @return string $this->base_url serverのURL
     */
    function setBaseUri() {

        $serverKbn = config('businessVolume.SERVER_KBN');
        if ($serverKbn === '3') {
            $this->base_uri = 'https://api.cloudsign.jp';
        } else {
            $this->base_uri = 'https://api-sandbox.cloudsign.jp';
        }
        return $this->getBaseUri();
    }
    function getBaseUri() {
        return $this->base_uri;
    }

    /*
     * @param string $client_id クラウドサイン クライアントID
     * @return string $this->client_id 内部に設定されたクライアントID
     */
    function setClientId($client_id) {
        $this->client_id = $client_id;
        return $this->getClientId();
    }
    function getClientId() {
        return $this->client_id;
    }

    function setHeaders($arr) {
        foreach ($arr as $k => $v) {
            $this->request_headers[$k] = $v;
        }
        return $this->getHeaders();
    }
    function getHeaders() {
        return $this->request_headers;
    }

    function setClient($client_options)
    {
        $options = array(
            'http_errors' => FALSE,
            'allow_redirects' => FALSE,
            'timeout' => 30,
        );
        foreach ($client_options as $k => $v) {
            $options[$k] = $v;
        }
        if (isset($this->base_uri)) {
            $options['base_uri'] = $this->base_uri;
        }
        $this->client = new Client($options);
        return TRUE;
    }

    function makeRequest($method, $url, $options=array()) {
        // $response = $this->client->request('GET', 'http://httpbin.org/headers');

        if (isset($options['headers'])) {
            if (!empty($this->request_headers)) {
                $options['headers'] = array_merge($this->request_headers, $options['headers']);
            }
        } else {
            if (!empty($this->request_headers)) {
                $options['headers'] = $this->request_headers;
            }
        }
        if (!empty($options['query']['client_id'])) {
            \Log::info('MakeRequestOptionsclient_id:'.$options['query']['client_id']);
            \Log::info('MakeRequestOptionsAgent:'.$options['headers']['User-Agent']);
        }
        if (!empty($options['form_params']['form_params'])) {
            \Log::info('MakeRequestOptionsclient_id:'.$options['form_params']['form_params']);
            \Log::info('MakeRequestOptionsAgent:'.$options['headers']['User-Agent']);
            \Log::info('MakeRequestOptionsAuthorization:'.$options['headers']['Authorization']);
        }
        $options['timeout'] = 200;
        $response = $this->client->request($method, $url, $options);
        \Log::info('MakeRequestResponseStatusCode:'. $response->getStatusCode());
        // $this->request['method'] = $this->bot->getMethod();
        $this->request['method'] = $method;
        if (isset($options['query'])) {
            if (is_array($options['query'])) {
                $this->request['uri'] = $url. '?'. http_build_query($options['query'], null, '&', PHP_QUERY_RFC3986);
            }
        } else {
            $this->request['uri'] = $url;
        }
        // $this->request['uri'] = (string) $this->bot->getUri();
        // $this->request['scheme'] = $this->bot->getUri()->getScheme();
        // $this->request['host'] = $this->bot->getUri()->getHost();
        // $this->request['port'] = $this->bot->getUri()->getPort();
        // $this->request['path'] = $this->bot->getUri()->getPath();
        // $this->request['query'] = $this->bot->getUri()->getQuery();
        if (isset($options['headers'])) {
            $this->request['headers'] = $options['headers'];
        } else {
            $this->request['headers'] = array();
        }
        /*
        if (isset($options['form_params'])) {
            $this->request['form_params'] = $options['form_params'];
        }
        */
        if (isset($this->request['options'])) {
            unset($this->request['options']);
        }
        foreach (array(
                    'title',
                    'note',
                    'message',
                    'template_id',
                    'can_transfer',
                    'comment',
                    'email',
                    'name',
                    'organization',
                    'access_code',
                    'language_code',
                    'participant_id',
                    'type',
                    'page',
                    'x',
                    'y',
                    'text',
                    'label'
        ) as $k) {
            if (isset($options['form_params'][$k])) {
                $this->request['options']['form_params'][$k] = $options['form_params'][$k];
            }
        }
        foreach (array(
                     'client_id',
                     'page',
                     'status',
                     'with_files',
                     'with_participants'
                 ) as $k) {
            if (isset($options['query'][$k])) {
                $this->request['options']['query'][$k] = $options['query'][$k];
            }
        }
        foreach (array(
                     'name',
                     'filename'
                 ) as $k) {
            // [0] に注意！
            if (isset($options['multipart'][0][$k])) {
                $this->request['options']['multipart'][0][$k] = $options['multipart'][0][$k];
            }
        }

        $this->response['status_code'] = $response->getStatusCode();
        $this->response['protocol_version'] = $response->getProtocolVersion();
        $this->response['reason'] = $response->getReasonPhrase();
        $this->response['headers'] = $this->normalizeHeaders($response->getHeaders());
        if ($response->getHeader('Content-Type')[0] === 'application/json') {
            $this->response['body'] = json_decode($response->getBody(), TRUE);
        } else {
            $this->response['body'] = $response->getBody()->getContents();
        }

        unset($options);

        return array(
            'request' => $this->request,
            'response' => $this->response,
        );
    }

    // http://docs.guzzlephp.org/en/stable/quickstart.html
    function normalizeHeaders($headers)
    {
        $ret = array();
        foreach ($headers as $name => $values) {
            $ret[$name] = implode('; ', $values);
        }
        return $ret;
    }




    // アクセストークンの取得にはクライアント ID
    private $sessionToken = '/token';

    /**
     * クラウドサイン Web API サーバー
     */
    public function setUp()
    {
        $this->client = new Client( [
            'base_uri' => $this->base_uri,
            'http_errors' => false
        ]);
    }

    /**
     * クラウドサインsession token を取得する。
     * @param $client_id
     * @return string
     */
    public function cloudsignToken($client_id)
    {
        $this->setUp();
        $response = $this->client->get($this->sessionToken.'?client_id='.$client_id);
        $body = $response->getBody();
        $data = json_decode($body, true);
        return $data;
    }

    /**
     * テスト用
     * @param $baseUri
     * @param $apiStr
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function get($baseUri, $apiStr)
    {
        $client = new Client([
            'base_uri' => $baseUri,
            'timeout'  => 10.0
        ]);
        $res = $client->get($apiStr);
        return $res;
    }


}